//
//  UITextView+Emoticon.swift
//  表情键盘
//
//  Created by LiHong on 15/11/7.
//  Copyright © 2015年 LiHong. All rights reserved.
//

import UIKit

extension UITextView {
    ///获取带表情图片的文本字符串
    func emoticonText() -> String? {
        var strM = ""
        
        attributedText.enumerateAttributesInRange(NSRange(location: 0, length: attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0), usingBlock: { (dict, range, _) -> Void in
            //判断是否是附件
            if let attachment = dict["NSAttachment"] as? LHTextAttachment {
                strM = attachment.name!
            } else {
                let str = (self.attributedText.string as NSString).substringWithRange(range)
                strM = str
            }
            
            
        })

        return strM
    }
    
    //MARK: - 把表情插入到textView中
    func insertEmoticon(emoticon: Emoticon) {
//        guard let textView = self.textView else {
//            print("textView为空")
//            return
//        }
        //如果是删除按钮
        if emoticon.removeEmoticon {
            deleteBackward()
        }
        
        
        // 插入emoji表情
        if let emoji = emoticon.emoji {
            insertText(emoji)
        }
        
        if let pngPath = emoticon.pngPath {
            // 附件,图片可以作为附件,附件可以添加到属性文本
            let attachment = LHTextAttachment()
            attachment.image = UIImage(contentsOfFile: pngPath)
            // 将表情图片的名称赋值
            attachment.name = emoticon.chs
            
            let height = font?.lineHeight ?? 10
            //设置附件的大小
            attachment.bounds = CGRect(x: 0, y: -4, width: height, height: height)
            
            //   let attrString = NSAttributedString(attachment: attachment)
            let attrString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
            attrString.addAttribute(NSFontAttributeName, value: font!, range: NSRange(location: 0, length: 1))
            
            let attrStringM = NSMutableAttributedString(attributedString: attributedText)
            
            let oldSelectedRange = selectedRange
            
            attrStringM.replaceCharactersInRange(oldSelectedRange, withAttributedString: attrString)
            
            attributedText = attrStringM
            
            selectedRange = NSRange(location: oldSelectedRange.location + 1, length: 0)
            
            delegate?.textViewDidChange!(self)
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: self)
        }
        
        
    }

    
    
}